﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Samurai.Wakizashi.Concurrency;

namespace Reactor.Messaging.ServiceBus
{
    public class DefaultMessageRegistry : IMessageRegistry
    {
        private readonly ReaderWriterLock _rwLock = new ReaderWriterLock();
        private readonly Dictionary<Type, List<string>> _messageDestinationRegistry = new Dictionary<Type, List<string>>();

        #region Implementation of IMessageRegistry

        /// <summary>
        /// Registers the type of the message, recording each desination the message is to be sent when published.
        /// </summary>
        /// <param name="messageType">Type of the message.</param>
        /// <param name="destinations">The destinations.</param>
        public void RegisterMessageType(Type messageType, IEnumerable<string> destinations)
        {
            using (new WriterLock(_rwLock, TimeSpan.FromSeconds(10)))
            {
                List<string> list = (_messageDestinationRegistry.ContainsKey(messageType))
                    ? _messageDestinationRegistry[messageType]
                    : new List<string>(destinations.Count());

                foreach (var destination in destinations.Where(destination => !list.Contains(destination)))
                    list.Add(destination);
            }
        }

        /// <summary>
        /// Gets the registered destinations for the specified message type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public IList<string> GetDestinationsForMessageType(Type type)
        {
            using (new ReaderLock(_rwLock, TimeSpan.FromSeconds(10)))
            {
                return !_messageDestinationRegistry.ContainsKey(type) 
                    ? new List<string>(0) 
                    : _messageDestinationRegistry[type];
            }
        }

        #endregion
    }
}
